using System;
using System.Collections.Generic;
using System.Net;
using System.Web.Mvc;
using Netkk.Common;
using Netkk.Common.Interfaces.Repositories;
using Netkk.Common.Interfaces.Services;
using Netkk.Common.Models;
using Netkk.Core;
using Netkk.Core.Auth;
using Netkk.Models;

namespace Netkk.Controllers
{
    public class NewsController : Controller
    {
        private readonly INewsService newsService;
        private readonly ITwitterRepository twitterRepository;

        public NewsController(
            INewsService newsService,
            ITwitterRepository twitterRepository)
        {
            this.newsService = newsService;
            this.twitterRepository = twitterRepository;
        }

        public ActionResult News(int? id)
        {
            IEnumerable<News> news = newsService.GetNextNews();

            NewsListModel model = LoadPagedNewsList(id ?? 1, news);

            return View(model);
        }

        public ActionResult NewsArchive(int? id)
        {
            IEnumerable<News> news = newsService.GetPastNews();

            NewsListModel model = LoadPagedNewsList(id ?? 1, news);

            return View(model);
        }

        private NewsListModel LoadPagedNewsList(int id, IEnumerable<News> news)
        {
            int totalPages;
            int currentPage = id == 0 ? 1 : id;

            news = news.PagedItems(10, currentPage - 1, out totalPages);

            List<NewsModel> newsModels = new List<NewsModel>();

            bool allowEditOrAdd = this.IsInRole(Roles.Admin);

            news.ForEach(n => newsModels.Add(NewsModel.Create(n, allowEditOrAdd)));

            NewsListModel model = new NewsListModel
            {
                News = newsModels,
                TotalPages = totalPages,
                CurrentPage = currentPage,
                ShowCreateNews = allowEditOrAdd
            };

            return model;
        }

        public ActionResult Details(string id)
        {
            Guid guid = id.ToOrDefault<Guid>();
            News news;
            bool isGuidRequest = false;

            if (guid != Guid.Empty)
            {
                isGuidRequest = true;
                news = newsService.GetNewsById(guid);
            }
            else
            {
                news = newsService.GetNewsByTitle(id);
            }

            if (news == null)
            {
                news = new News
                {
                    Title = "Termin nicht bekannt",
                    Date = DateTime.Now
                };
            }

            if (isGuidRequest)
            {
                return this.RedirectToActionWithId("News", "Details", Tools.GetCleanUrl(news.Title));
            }

            NewsModel model = NewsModel.Create(news, this.IsInRole(Roles.Admin));

            return View(model);
        }

        [UserInRole(Roles.Admin)]
        public ActionResult Create()
        {
            NewsModel model = NewsModel.Create();

            return View(model);
        }

        [UserInRole(Roles.Admin)]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Create(FormCollection collection)
        {
            NewsModel model = NewsModel.Create();

            try
            {
                UpdateModel(model, new[] { "Title", "Date", "Teaser", "Text" });

                News news = model.MapNews();

                if (!newsService.SaveNews(news))
                {
                    return View(model);
                }

                try
                {
                    // Send Tweet for new appointment.
                    twitterRepository.UpdateStatus(
                        string.Format("Neue News {0}: {1} - {2}",
                                      news.Date,
                                      news.Title,
                                      string.Format("http://dotnetkk.de/News/Details/{0}",
                                                    Tools.GetCleanUrl(news.Title))));
                }
                catch (WebException)
                {

                }

                return RedirectToAction("News", "News");
            }
            catch
            {
                return View(model);
            }
        }

        [UserInRole(Roles.Admin)]
        public ActionResult Edit(Guid id)
        {
            News news = newsService.GetNewsById(id);

            news = news ?? new News
                               {
                                   Title = "Termin nicht bekannt",
                                   Date = DateTime.Now
                               };

            NewsModel model = new NewsModel
            {
                CleanTitle = Tools.GetCleanUrl(news.Title),
                Title = news.Title,
                Teaser = news.Teaser,
                Text = news.Text,
                Date = news.Date,
                Id = news.Id,
                ShowEditNews = this.IsInRole(Roles.Admin)
            };

            return View(model);
        }

        [UserInRole(Roles.Admin)]
        [AcceptVerbs(HttpVerbs.Post)]
        [ValidateInput(false)]
        public ActionResult Edit(Guid id, FormCollection collection)
        {
            NewsModel model = NewsModel.Create();
            try
            {
                UpdateModel(model, new[] { "Title", "Date", "Teaser", "Text" });

                News news = model.MapNews(id);

                if (!newsService.SaveNews(news))
                {
                    return View(model);
                }

                return RedirectToAction("News", "News");
            }
            catch
            {
                return View(model);
            }
        }

        [UserInRole(Roles.Admin)]
        public ActionResult Delete(Guid id)
        {
            News news = newsService.GetNewsById(id);

            newsService.DeleteNews(news);

            return RedirectToAction("News", "News");
        }

    }
}
